﻿#include <iostream>
#include <fstream>
#include <cstring>
#include <arpa/inet.h>
#include <unistd.h>

#define PORT 12345
#define CHUNK_SIZE 1024

void receiveFile(const char* outputFilename) {
    int sock;
    struct sockaddr_in localAddr;
    char buffer[CHUNK_SIZE];

    // 创建套接字
    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("socket");
        exit(1);
    }

    // 绑定本地地址
    memset(&localAddr, 0, sizeof(localAddr));
    localAddr.sin_family = AF_INET;
    localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    localAddr.sin_port = htons(PORT);

    if (bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) < 0) {
        perror("bind");
        close(sock);
        exit(1);
    }

    // 打开输出文件
    std::ofstream file(outputFilename, std::ios::binary);
    if (!file.is_open()) {
        perror("打开输出文件失败");
        close(sock);
        exit(1);
    }

    // 接收数据
    while (true) {
        ssize_t bytesReceived = recvfrom(sock, buffer, CHUNK_SIZE, 0, NULL, NULL);
        if (bytesReceived < 0) {
            perror("recvfrom");
            break;
        }

        // 检查结束标志
        if (strncmp(buffer, "END", bytesReceived) == 0) {
            std::cout << "文件接收完成。" << std::endl;
            break;
        }

        file.write(buffer, bytesReceived);
    }

    file.close();
    close(sock);
}

int main() {
    const char* outputFilename = "received_file_udp.dat"; // 接收保存的文件名
    receiveFile(outputFilename);
    return 0;
}
